package com.andaily.infrastructure;

import com.andaily.domain.log.FrequencyMonitorLog;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Wrapper HttpClient operations
 * Default request method: GET
 *
 * @author Shengzhao Li
 */
public class HttpClientHandler {

    protected static final Logger LOGGER = LoggerFactory.getLogger(HttpClientHandler.class);
    //Convert mill seconds to second unit
    protected static final int MS_TO_S_UNIT = 1000;
    //Normal http response code
    protected static final int NORMAL_RESPONSE_CODE = 200;
    //https prefix
    protected static final String HTTPS = "https";

    protected static HttpsTrustManager httpsTrustManager = new HttpsTrustManager();

    protected String url;

    protected int maxConnectionSeconds = 0;

    public HttpClientHandler(String url) {
        this.url = url;
    }

    public HttpClientHandler maxConnectionSeconds(int maxConnectionSeconds) {
        this.maxConnectionSeconds = maxConnectionSeconds;
        return this;
    }

    public FrequencyMonitorLog handleAndGenerateFrequencyMonitorLog() {
        FrequencyMonitorLog monitorLog = new FrequencyMonitorLog();

        final long start = System.currentTimeMillis();
        try {
            final HttpResponse response = sendRequest();

            monitorLog.normal(isNormal(response))
                    .responseSize(responseSize(response))
                    .costTime(costTime(start));

        } catch (Exception e) {
            monitorLog.costTime(costTime(start)).normal(false)
                    .remark(e.getClass().getSimpleName() + ": " + e.getMessage());
            LOGGER.debug("Send request to url[" + url + "] failed", e);
        }

        return monitorLog;
    }

    protected long responseSize(HttpResponse response) {
        return response.getEntity().getContentLength();
    }

    protected long costTime(long start) {
        return System.currentTimeMillis() - start;
    }

    protected boolean isNormal(HttpResponse response) {
        return response.getStatusLine().getStatusCode() == NORMAL_RESPONSE_CODE;
    }

    protected HttpResponse sendRequest() throws Exception {
        HttpRequestBase request = retrieveHttpRequest();
        addRequestParams(request);
        HttpClient client = retrieveHttpClient();
        return client.execute(request);
    }

    protected HttpClient retrieveHttpClient() {
        final HttpClient httpClient = new DefaultHttpClient();
        if (isHttps()) {
            initialHttpsSetting(httpClient);
        }
        return httpClient;
    }

    private void initialHttpsSetting(HttpClient httpClient) {
        SSLContext sslContext = createSSLContext();
        SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme(HTTPS, 443, ssf));
        LOGGER.debug("Initial 'HTTPS' SSLSocketFactory [{}] for URL: {}", ssf, url);
    }

    private SSLContext createSSLContext() {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new HttpsTrustManager[]{httpsTrustManager}, null);
            return sslContext;
        } catch (Exception e) {
            throw new IllegalStateException("Create SSLContext error", e);
        }
    }

    private boolean isHttps() {
        return url.toLowerCase().startsWith(HTTPS);
    }

    protected HttpRequestBase retrieveHttpRequest() {
        return new HttpGet(url);
    }

    protected void addRequestParams(HttpRequestBase request) {
        if (this.maxConnectionSeconds <= 0) {
            return;
        }
        final BasicHttpParams params = new BasicHttpParams();

        final int maxConnMillSeconds = this.maxConnectionSeconds * MS_TO_S_UNIT;
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, maxConnMillSeconds);
        //设置数据传输时间   pull-request #1
        //避免虽然连接成功但服务器端长时间无返回值，导致达不到预期监控效果的情况
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, maxConnMillSeconds);
        request.setParams(params);
    }


    /**
     * Default X509TrustManager implement
     */
    private static class HttpsTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            //ignore
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            //ignore
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}